const path = require('path')
const request = require('request')
const cheerio = require('cheerio')
const coinArr = ['eth', 'eos', 'ada', 'btm']

const rp = (url) => {
  return new Promise((resolve, reject) => {
    request({url: url, timeout: 5000 }, (error, response, body) => {
      if (error) {
        return reject(error)
      }
      resolve(body)
    })
  })
}

;(async () => {
  let priceObj = {}
  // console.log(`------------[coin crawler run]------------`)
  for (let i = 0; i < coinArr.length; i++) {
    let crawlUrl = `https://otcbtc.io/sell_offers?currency=${coinArr[i]}&fiat_currency=cny&payment_type=all`
    await rp(crawlUrl)
      .then(data => {
        let $ = cheerio.load(data)
        let price = $('.long-solution-list').find('.list-content').eq(0).find('.price').text()
        price = price.split('\n')[2].replace(/\s+/g, '').replace(/\,/g, '')
        priceObj[coinArr[i]] = (+price).toFixed(2)
      })
      .catch(err => {
    })
  }
  process.send({ priceObj })
  process.exit(0)
})()